<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户类型" prop="field101">
        <el-radio-group v-model="formData.field104" size="medium">
          <el-radio v-for="(item, index) in field101Options" :key="index" :label="item.yhlxId"
                    :disabled="item.disabled">{{item.yhlxName}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="活动规则" prop="field102">
        <el-radio-group v-model="formData.field105" size="medium">
          <el-radio v-for="(item, index) in field101Options1" :key="index" :label="item.hdgzId"
                    :disabled="item.disabled">{{item.hdgzName}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="优惠类型" prop="field103">
        <el-radio-group v-model="formData.field106" size="medium">
          <el-radio v-for="(item, index) in field101Options2" :key="index" :label="item.hdlxId"
                    :disabled="item.disabled">{{item.hdlxName}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效范围" style="display: flex; align-items: center;">
        <div style="display: flex; margin-right: 30px;">
          <el-input
            v-model="minyx"
            placeholder="最小有效范围"
            clearable
            @keyup.enter.native="handleQuery"
            style="flex: 1; margin-right: 10px;width: 50px"
          />
          <el-input
            v-model="bigyx"
            placeholder="最大有效范围"
            clearable
            @keyup.enter.native="handleQuery"
            style="flex: 1;"
          />
        </div>
      </el-form-item>
      <el-form-item label="活动创建">
        <el-date-picker
          v-model="time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动状态" prop="ptyhZt">
        <el-select v-model="queryParams.ptyhZt" placeholder="请选择活动状态" clearable>
          <el-option
            v-for="dict in dict.type.pingtaiyouhui"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:pingtaiyouhui:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:pingtaiyouhui:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:pingtaiyouhui:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:pingtaiyouhui:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pingtaiyouhuiList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="ptyhId" />
      <el-table-column label="活动类型" align="center" prop="hudongleixing.hdlxName" />
      <el-table-column label="活动规则" align="center" prop="huodongguize.hdgzName" />
      <el-table-column label="用户类型" align="center" prop="yonghuleixing.yhlxName" />
      <el-table-column label="有效期" align="center" prop="ptyhYx" />
      <el-table-column label="应用范围" align="center" prop="ptyhFw" />
      <el-table-column label="使用量" align="center" prop="yonghuYhid" />
      <el-table-column label="创建时间" align="center" prop="ptyhCreatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ptyhCreatetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="ptyhZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pingtaiyouhui" :value="scope.row.ptyhZt"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:pingtaiyouhui:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:pingtaiyouhui:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台优惠活动，存储平台上的各种优惠活动信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户类型" prop="field101">
          <el-radio-group v-model="formData.field101" size="medium">
            <el-radio v-for="(item, index) in field101Options" :key="index" :label="item.yhlxId"
                      :disabled="item.disabled">{{item.yhlxName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动规则" prop="field102">
          <el-radio-group v-model="formData.field102" size="medium">
            <el-radio v-for="(item, index) in field101Options1" :key="index" :label="item.hdgzId"
                      :disabled="item.disabled">{{item.hdgzName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠类型" prop="field103">
          <el-radio-group v-model="formData.field103" size="medium">
            <el-radio v-for="(item, index) in field101Options2" :key="index" :label="item.hdlxId"
                      :disabled="item.disabled">{{item.hdlxName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="有效天数" prop="ptyhYx">
          <el-input v-model="form.ptyhYx" placeholder="请输入有效天数" />
        </el-form-item>
        <el-form-item label="应用范围" prop="ptyhFw">
          <el-input v-model="form.ptyhFw" placeholder="请输入应用范围" />
        </el-form-item>
        <el-form-item label="创建时间" prop="ptyhCreatetime">
          <el-date-picker clearable
            v-model="form.ptyhCreatetime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态" prop="ptyhZt">
          <el-radio-group v-model="form.ptyhZt">
            <el-radio
              v-for="dict in dict.type.pingtaiyouhui"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPingtaiyouhui,
  getPingtaiyouhui,
  delPingtaiyouhui,
  addPingtaiyouhui,
  updatePingtaiyouhui,
  yonghuleixinglist, huodongguizelist, hudongleixinglist
} from "@/api/system/pingtaiyouhui";

export default {
  name: "Pingtaiyouhui",
  dicts: ['pingtaiyouhui'],
  data() {
    return {
      time:'',
      minyx:null,
      bigyx:null,
      formData: {
        field101: undefined,
        field102: undefined,
        field103: undefined,
        field104: undefined,
        field105: undefined,
        field106: undefined,
      },
      field101Options: [{
        "yhlxName": "选项一",
        "yhlxId": 1
      }],
      field101Options1: [{
        "hdgzName": "选项一",
        "hdgzId": 1
      }],
      field101Options2: [{
        "hdlxName": "选项一",
        "hdlxId": 1
      }],
      field101Options3: [{
        "hdlxName": "选项一",
        "hdlxId": 1
      }],
      field101Options4: [{
        "hdlxName": "选项一",
        "hdlxId": 1
      }],
      field101Options5: [{
        "hdlxName": "选项一",
        "hdlxId": 1
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台优惠活动，存储平台上的各种优惠活动信息表格数据
      pingtaiyouhuiList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hdlxId: null,
        hdgzId: null,
        yhlxId: null,
        ptyhYx: null,
        ptyhFw: null,
        ptyhCreatetime: null,
        ptyhZt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hdlxId: [
          { required: true, message: "活动类型ID不能为空", trigger: "blur" }
        ],
        yhlxId: [
          { required: true, message: "用户类型ID不能为空", trigger: "blur" }
        ],
        ptyhYx: [
          { required: true, message: "有效天数不能为空", trigger: "blur" }
        ],
        ptyhZt: [
          { required: true, message: "活动状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.yhlx();
    this.hdgz();
    this.hdlx();
  },
  methods: {
    //时间格式转化
    getGoodTime(time) {
      // 尝试将输入字符串解析为Date对象
      let date = new Date(time);
      // 检查Date对象是否有效（即不是Invalid Date）
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date string');
      }
      // 提取年、月、日、时、分、秒
      // 月份从0开始，所以要加1；日期、小时、分钟、秒直接使用
      // 使用padStart来确保月份、日期、小时、分钟、秒始终是两位数
      const year = time.getFullYear();
      const month = String(time.getMonth() + 1).padStart(2, '0');
      const day = String(time.getDate()).padStart(2, '0');
      const hours = String(time.getHours()).padStart(2, '0');
      const minutes = String(time.getMinutes()).padStart(2, '0');
      const seconds = String(time.getSeconds()).padStart(2, '0');

      // 拼接成所需的格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.formData.field104 && '' != this.formData.field104){
        this.queryParams.yhlxId = this.formData.field104;
      }
      if (null != this.formData.field105 && '' != this.formData.field105){
        this.queryParams.hdgzId = this.formData.field105;
      }
      if (null != this.formData.field106 && '' != this.formData.field106){
        this.queryParams.hdlxId = this.formData.field106;
      }
      if (null != this.minyx && '' !== this.minyx && null != this.bigyx && '' != this.bigyx) {
        this.queryParams.params["minyx"] = this.minyx;
        this.queryParams.params["bigyx"] = this.bigyx;
      }
      if (null != this.time && '' !== this.time) {
        this.queryParams.params["starttime"] = this.getGoodTime(this.time[0]);
        this.queryParams.params["endtime"] = this.getGoodTime(this.time[1]);
      }
      listPingtaiyouhui(this.queryParams).then(response => {
        this.pingtaiyouhuiList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    yhlx(){
        yonghuleixinglist(null).then(response => {
          this.field101Options = response.rows;
          console.log(this.field101Options);
      })

    },
    hdgz(){
      huodongguizelist(null).then(response => {
        this.field101Options1 = response.rows;
        console.log(this.field101Options1);
      })
    },
    hdlx(){
      hudongleixinglist(null).then(response => {
        this.field101Options2 = response.rows;
        console.log(this.field101Options2);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ptyhId: null,
        hdlxId: null,
        hdgzId: null,
        yhlxId: null,
        ptyhYx: null,
        ptyhFw: null,
        ptyhCreatetime: null,
        ptyhZt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      window.location.reload();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ptyhId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加or修改";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ptyhId = row.ptyhId || this.ids
      getPingtaiyouhui(ptyhId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改or增加";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.yhlxId = this.formData.field101
      this.form.hdgzId = this.formData.field102
      this.form.hdlxId = this.formData.field103
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ptyhId != null) {
            updatePingtaiyouhui(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPingtaiyouhui(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ptyhIds = row.ptyhId || this.ids;
      this.$modal.confirm('是否确认删除平台优惠活动，存储平台上的各种优惠活动信息编号为"' + ptyhIds + '"的数据项？').then(function() {
        return delPingtaiyouhui(ptyhIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/pingtaiyouhui/export', {
        ...this.queryParams
      }, `pingtaiyouhui_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
